package com.live.shop.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.model.AudioFileModel;
import com.live.shop.model.MusicModel;
import com.live.shop.sql.MusicListDatabase;
import com.live.shop.tool.FileUtils;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastBottomUtils;

import java.io.IOException;
import java.util.List;

public class MusicListActivity extends BaseActivity {
    ImageButton music_back;
    TextView music_add;
    RecyclerView music_recyclerview;
    List<MusicModel> list ;
    MusicListDatabase musicDb;
    boolean isPlaying = false;
    int PlayingPosition = -1;
    //播放器
    MediaPlayer mediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_list);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);

        music_back = findViewById(R.id.music_back);
        music_add = findViewById(R.id.music_add);
        music_recyclerview = findViewById(R.id.music_recyclerview);
        music_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        music_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), AudioFileListActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        musicDb = new MusicListDatabase(getApplicationContext());
        init();
    }
    public void init(){
        list = musicDb.selectAll();
        adapter = new MyAdapter();
        music_recyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        music_recyclerview.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    private MyAdapter adapter;

    class MyAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyAdapter.MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_music, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            MyAdapter.MyViewHolder mholder = (MyAdapter.MyViewHolder) holder;
            MusicModel musicModel = list.get(holder.getBindingAdapterPosition());

            mholder.item_music_name.setText(musicModel.getMusicName());
            if(PlayingPosition == holder.getBindingAdapterPosition()){
                mholder.item_music_play.setImageResource(R.mipmap.icon_audio_pause);
            }else{
                mholder.item_music_play.setImageResource(R.mipmap.icon_audio_player);
            }
            mholder.item_music_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String music_url = musicModel.getMusicUrl();
                    if(!FileUtils.getFileExist(getApplicationContext(),music_url)){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"音频文件不存在！");
                        return;
                    }
                    if(isPlaying){
                        //播放中，则取消播放
                        isPlaying = false;
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        if(PlayingPosition == position){
                            //暂停
                            PlayingPosition = -1;
                            notifyDataSetChanged();
                            return;
                        }
                    }
                    if(PlayingPosition != holder.getBindingAdapterPosition()){
                        //开始播放
                        PlayingPosition = holder.getBindingAdapterPosition();
                        isPlaying = true;
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        try {
                            mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(music_url));
                            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mediaPlayer) {
                                    mediaPlayer.release();
                                    isPlaying = false;
                                    PlayingPosition = -1;
                                }
                            });
                            mediaPlayer.prepare();
                            mediaPlayer.start();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    notifyDataSetChanged();
                }
            });
            mholder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog_change_name(holder.getBindingAdapterPosition(),musicModel.getMusicUrl(),"");
                }
            });
            mholder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    dialog_item_delete(holder.getBindingAdapterPosition());
                    return true;
                }
            });
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView item_music_name;
            ImageView item_music_play;

            public MyViewHolder(View itemView) {
                super(itemView);
                item_music_name = itemView.findViewById(R.id.item_music_name);
                item_music_play = itemView.findViewById(R.id.item_music_play);
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
            if (data != null) {
                AudioFileModel model = (AudioFileModel) data.getSerializableExtra("model");
                dialog_change_name(-1,model.getUrl(),model.getDisplayName());
            }
        }
    }

    public void dialog_item_delete(int position){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_item_delete);
        final TextView diaglog_delete_ok = window.findViewById(R.id.diaglog_delete_ok);
        final TextView diaglog_delete_no = window.findViewById(R.id.diaglog_delete_no);
        diaglog_delete_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adapter.notifyItemRemoved(position);
                musicDb.deleteOne(list.get(position).getMusicId());
                list.remove(position);
                dialog.dismiss();
            }
        });
        diaglog_delete_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }
    public void dialog_change_name(int position,String filePath,String fileName){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.setView(new EditText(this));
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_music);
        final EditText dialog_music_edittext = window.findViewById(R.id.dialog_music_edittext);
        final TextView dialog_music_path = window.findViewById(R.id.dialog_music_path);
        final TextView dialog_music_no = window.findViewById(R.id.dialog_music_no);
        final TextView dialog_music_ok = window.findViewById(R.id.dialog_music_ok);

        if(position == -1){
            dialog_music_edittext.setText(fileName);
        }else{
            dialog_music_edittext.setText(list.get(position).getMusicName());
        }

        dialog_music_path.setText(filePath);
        dialog_music_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_music_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String music_name = dialog_music_edittext.getText().toString();
                if(position == -1){
                    //新增
                    MusicModel musicModel = new MusicModel();
                    musicModel.setMusicUrl(filePath);
                    musicModel.setMusicName(music_name);
                    musicDb.insertData(musicModel);
                    init();
                }else{
                    //编辑
                    list.get(position).setMusicName(music_name);
                    musicDb.updateData(list.get(position));
                    adapter.notifyDataSetChanged();
                }
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放MediaPlayer资源
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}